from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.system.models import Files
from apps.system.serializers.files import FilesSerializer


class FilesView(ModelViewSet):
    queryset = Files.objects.all()
    serializer_class = FilesSerializer

    def create(self, request, *args, **kwargs):
        file = request.data.get('file')
        if not file:
            return Response({'msg': '文件不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        size = file.size  # 获取文件大小
        name = file.name  # 获取文件名称
        file_type = file.content_type  # 获取文件类型

        file_type_list = [
            'text/plain',
            'application/pdf',
            'application/msword',
            'application/vnd.ms-excel',
            'application/vnd.ms-powerpoint'
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'application/x-zip-compressed'
        ]

        if size > 1024 * 2000:
            return Response({'msg': '文件大小不能超过2mb！您的图片大小为：{}mb'.format(round(size / (1024 * 1024), 2))},
                            status=status.HTTP_400_BAD_REQUEST)
        elif file_type not in file_type_list:
            return Response({'msg': '您上传的文件类型不合格！'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            if request.data.get('name'):
                name = request.data.get('name')
            else:
                name = name.replace('.'+name.split('.')[-1], "")
            save_data = {
                'name': name,
                'size': size,
                'file': file
            }
            serializer = self.get_serializer(data=save_data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
